package ichubclicommon

import (
	"fmt"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/baseutils/jsonutils"
	"gitee.com/ichub/webcli/common/ichublog"
	"strings"
)

/*
@Title    文件名称: ichub_ruledata.go
@Description  描述: 有芯规则引擎执行的数据值对象

@Author  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
@Update  作者: leijianming@163.com  时间(2024-02-18 22:38:21)
*/
type RuleData struct {
	//执行模式：0单一模式10串20并30混40逆50桶
	Mode int `json:"mode"`
	//must param
	Id string `json:"id"`
	//规则名称
	Name string `json:"Name"`
	//规则define
	Rule string `json:"rule"`
	//参数 json string
	Param string `json:"param"`

	//option params
	//返回结果
	Result string `json:"-"`
	//比对值
	Exp string `json:"-"`
	//zip bool
}

func (ruleData *RuleData) Clone() *RuleData {
	r := *ruleData
	return &r
}

func (ruleData *RuleData) check() error {
	if len(ruleData.Rule) == 0 {
		err := basedto.NewIchubError(400, "rule请求规则为空！")
		return err
	}
	if len(ruleData.Param) == 0 {
		err := basedto.NewIchubError(400, "rule规则参数为空")
		return err
	}

	return nil
}
func (ruleData *RuleData) Line(i int) string {
	var lines = strings.Split(ruleData.Rule, "\n")
	return lines[i-1]
}
func (ruleData *RuleData) LogLines() *RuleData {
	fmt.Println("LogLines: ")
	fmt.Println(
		ruleData.ToLines().String(),
	)
	return ruleData

}

func (ruleData *RuleData) ToLines() *strings.Builder {
	builder := &strings.Builder{}
	var lines = strings.Split(ruleData.Rule, "\n")

	builder.WriteString("\r\n")
	for i, v := range lines {
		var msg = fmt.Sprintf("Line %03d: %s\r\n", i+1, v)
		builder.WriteString(msg)
	}
	return builder
}

func NewRuleData(Rule, Param string) *RuleData {
	return &RuleData{
		Rule:  Rule,
		Param: Param,
	}
}
func RuleDataComparator(a, b interface{}) int {

	return strings.Compare(a.(*RuleData).Param, b.(*RuleData).Param)

}

// Log 打印规则引擎入参数据
func (ruleData *RuleData) Log() *RuleData {
	ruleData.Rule2IdName()
	var data = ruleData.Clone()
	data.Rule = ruleData.ToLines().String()
	ichublog.IchubLog.Println("IchubContext=", data.ToString())
	fmt.Println("IchubContext RULE=", data.Rule)

	return ruleData
}

// rule "pay-simple-compute-001" "简单计算工资示例" salience 0
func (ruleData *RuleData) Rule2IdName() *RuleData {

	ruleData.Id = strings.Trim(ruleData.Id, " ")
	if len(ruleData.Id) > 0 {
		return ruleData
	}

	var lines = strings.Split(ruleData.Rule, "\n")
	for _, v := range lines {
		if strings.Contains(v, "rule ") && strings.Contains(v, "salience") { //titles := strings.Split(v, " ")

			var titles = strings.Split(v, `"`) //re.FindAllStringSubmatch(v, -1)
			ruleData.Id = titles[1]
			ruleData.Name = titles[3]
		}

	}
	return ruleData
}

func (ruleData *RuleData) ToString() string {
	return jsonutils.ToJsonPretty(ruleData)
}

func (ruleData *RuleData) String() string {

	return jsonutils.ToJsonPretty(ruleData)

}
